package cn.iotnc.camera.base

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import cn.iotnc.camera.model.BaseResponse
import cn.iotnc.camera.model.IotncThrowable
import cn.iotnc.camera.model.IotncThrowable.Companion.SUCCESS
import cn.iotnc.camera.model.IotncThrowable.Companion.handleException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error


abstract class BaseViewModel(val app: Application) : AndroidViewModel(app), AnkoLogger {

    fun launch(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch { block() }

    fun <T> launchNullable(
        block: suspend CoroutineScope.() -> T,
        success: (T?) -> Unit,
        error: (Throwable) -> Unit = {},
        complete: () -> Unit = {}
    ) = launch {
        try {
            val response = block()
            success(response)
        } catch (e: Throwable) {
            error { "launchNullable: $block, exception=$e" }
            error(e.handleException())
        } finally {
            complete()
        }
    }

    fun <T> launchNotNull(
        block: suspend CoroutineScope.() -> T,
        success: (T) -> Unit,
        error: (Throwable) -> Unit = {},
        complete: () -> Unit = {}
    ) = launch {
        try {
            val response = block()
            success(response)
        } catch (e: Throwable) {
            error { "launchNotNull: $block, exception=$e" }
            error(e.handleException())
        } finally {
            complete()
        }
    }

//    companion object {
//        fun <T> BaseResponse<T>.toResult(): Result {
//            return if (errorCode == SUCCESS) {
//                if (data != null)
//                    Result.success(data)
//                else Result.failure(IotncThrowable(-1, "数据为空"))
//            } else {
//                Result.failure(IotncThrowable(errorCode, errorDesc))
//            }
//        }
//    }
}